<template>
  <view class="detail-container">
    <!-- 头部导航 -->
    <view class="detail-header">
      <text class="icon-back" @click="goBack">‹</text>
      <text class="header-title">商品详情</text>
      <text class="icon-share" @click="shareProduct">↗</text>
    </view>

    <!-- 商品图片轮播 -->
    <swiper class="product-swiper" indicator-dots autoplay circular>
      <swiper-item v-for="(img, index) in productDetail.images" :key="index">
        <image :src="img" class="swiper-image" mode="aspectFill" />
      </swiper-item>
    </swiper>

    <!-- 商品基本信息 -->
    <view class="product-info">
      <view class="price-section">
        <text class="current-price">¥{{ productDetail.price }}</text>
        <text class="original-price" v-if="productDetail.originalPrice">¥{{ productDetail.originalPrice }}</text>
        <text class="discount" v-if="productDetail.discount">{{ productDetail.discount }}折</text>
      </view>
      <text class="product-title">{{ productDetail.title }}</text>
      <text class="product-subtitle">{{ productDetail.subtitle }}</text>
      
      <view class="sales-info">
        <text>销量: {{ productDetail.sales }}</text>
        <text>库存: {{ productDetail.stock }}</text>
        <text>收藏: {{ productDetail.favorites }}</text>
      </view>
    </view>

    <!-- 商品规格选择 -->
    <view class="spec-section" v-if="productDetail.specifications && productDetail.specifications.length">
      <view class="section-header" @click="showSpecModal">
        <text class="section-title">选择规格</text>
        <view class="selected-spec">
          <text v-if="selectedSpec">{{ getSpecName(selectedSpec) }}</text>
          <text v-else class="placeholder">请选择规格</text>
          <text class="arrow">›</text>
        </view>
      </view>
    </view>

    <!-- 商品评价 -->
    <view class="review-section">
      <view class="section-header" @click="goToReviewList">
        <view class="review-title">
          <text class="section-title">商品评价</text>
          <text class="review-rating">
            <text class="rating-score">{{ productDetail.rating || 4.8 }}</text>
            <text class="rating-stars">★★★★★</text>
          </text>
        </view>
        <view class="more-info">
          <text class="review-count">查看全部{{ productDetail.reviewCount || 128 }}条评价</text>
          <text class="arrow">›</text>
        </view>
      </view>
      
      <!-- 精选评价 -->
      <view class="featured-reviews" v-if="featuredReviews.length">
        <view 
          v-for="review in featuredReviews" 
          :key="review.id"
          class="review-item"
        >
          <view class="reviewer-info">
            <image :src="review.avatar" class="reviewer-avatar" mode="aspectFit" />
            <text class="reviewer-name">{{ review.nickname }}</text>
            <text class="review-time">{{ review.time }}</text>
          </view>
          <view class="review-content">
            <text class="review-text">{{ review.content }}</text>
            <view class="review-images" v-if="review.images && review.images.length">
              <image 
                v-for="(img, index) in review.images" 
                :key="index"
                :src="img" 
                class="review-image"
                mode="aspectFill"
                @click="previewImage(review.images, index)"
              />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <view class="detail-content">
        <rich-text :nodes="productDetail.detailContent"></rich-text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="detail-footer">
      <view class="footer-actions">
        <view class="action-item" @click="toggleFavorite">
          <text class="icon-favorite" :class="{ favorited: isFavorited }">♥</text>
          <text class="action-text">收藏</text>
        </view>
        <view class="action-item" @click="goToCart">
          <text class="icon-cart">🛒</text>
          <text class="action-text">购物车</text>
          <view v-if="cartCount > 0" class="cart-badge">{{ cartCount > 99 ? '99+' : cartCount }}</view>
        </view>
      </view>
      <view class="footer-buttons">
        <button class="btn-add-cart" @click="showSpecModal">加入购物车</button>
        <button class="btn-buy-now" @click="showSpecModal">立即购买</button>
      </view>
    </view>

    <!-- 规格选择弹窗 -->
    <view class="spec-modal" v-if="showModal" @click="hideSpecModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <image :src="productDetail.images[0]" class="modal-product-image" mode="aspectFill" />
          <view class="modal-product-info">
            <text class="modal-price">¥{{ productDetail.price }}</text>
            <text class="modal-stock">库存{{ productDetail.stock }}件</text>
            <text class="modal-selected" v-if="selectedSpec">已选：{{ getSpecName(selectedSpec) }}</text>
          </view>
          <text class="modal-close" @click="hideSpecModal">×</text>
        </view>

        <!-- 规格选择 -->
        <view class="modal-specs" v-if="productDetail.specifications">
          <view class="spec-group" v-for="spec in productDetail.specifications" :key="spec.id">
            <text class="spec-label">{{ spec.name }}</text>
            <view class="spec-options">
              <view 
                v-for="option in spec.options" 
                :key="option.id"
                class="spec-option"
                :class="{ 
                  active: selectedSpec === option.id,
                  disabled: !option.available 
                }"
                @click="selectSpec(option)"
              >
                {{ option.value }}
              </view>
            </view>
          </view>
        </view>

        <!-- 数量选择 -->
        <view class="quantity-selector">
          <text class="quantity-label">购买数量</text>
          <view class="quantity-control">
            <text 
              class="quantity-btn minus" 
              :class="{ disabled: quantity <= 1 }"
              @click="decreaseQuantity"
            >-</text>
            <text class="quantity-value">{{ quantity }}</text>
            <text 
              class="quantity-btn plus" 
              :class="{ disabled: quantity >= productDetail.stock }"
              @click="increaseQuantity"
            >+</text>
          </view>
        </view>

        <view class="modal-actions">
          <button class="modal-btn add-cart" @click="addToCart">加入购物车</button>
          <button class="modal-btn buy-now" @click="buyNow">立即购买</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      productId: null,
      productDetail: {},
      selectedSpec: null,
      isFavorited: false,
      quantity: 1,
      showModal: false,
      cartCount: 0,
      featuredReviews: [
        {
          id: 1,
          nickname: '书友123',
          avatar: '/static/avatar-default.png',
          time: '2024-01-15',
          content: '这本书内容很丰富，印刷质量也很好，值得购买！',
          images: ['/static/book1.jpg', '/static/book2.jpg'],
          rating: 5
        },
        {
          id: 2,
          nickname: '阅读爱好者',
          avatar: '/static/avatar-default.png',
          time: '2024-01-10',
          content: '快递很快，书包装完好，内容正是我需要的。',
          rating: 4
        }
      ]
    }
  },
  onLoad(options) {
    this.productId = options.id
    console.log('接收到的商品ID:', this.productId)
    this.loadProductDetail()
    this.updateCartCount()
  },
  onShow() {
    this.updateCartCount()
  },
  methods: {
    async loadProductDetail() {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 使用模拟数据
        this.productDetail = this.generateMockDetail()
        
        // 默认选择第一个规格
        if (this.productDetail.specifications && this.productDetail.specifications.length > 0) {
          const firstSpec = this.productDetail.specifications[0]
          if (firstSpec.options && firstSpec.options.length > 0) {
            this.selectedSpec = firstSpec.options[0].id
          }
        }
        
        // 检查是否已收藏
        this.checkFavoriteStatus()
        
      } catch (error) {
        console.error('加载商品详情失败:', error)
        this.productDetail = this.generateMockDetail()
      } finally {
        uni.hideLoading()
      }
    },

    generateMockDetail() {
      const bookId = parseInt(this.productId)
      const categories = ['文学小说', '科技科普', '经济管理', '教育学习', '艺术设计', '生活休闲']
      const categoryId = (bookId % 6) + 1
      
      return {
        id: bookId,
        title: `图书 ${bookId} - ${categories[categoryId-1]}`,
        subtitle: '这是一本非常优秀的图书，内容丰富，情节引人入胜',
        price: (Math.random() * 50 + 10).toFixed(2),
        originalPrice: (Math.random() * 60 + 20).toFixed(2),
        discount: Math.floor(Math.random() * 3 + 8),
        stock: Math.floor(Math.random() * 100),
        sales: Math.floor(Math.random() * 1000),
        favorites: Math.floor(Math.random() * 500),
        rating: 4.8,
        reviewCount: 128,
        images: [
          '/static/book1.jpg',
          '/static/book2.jpg',
          '/static/book3.jpg'
        ],
        specifications: [
          {
            id: 1,
            name: '版本',
            options: [
              { id: 1, value: '平装版', available: true },
              { id: 2, value: '精装版', available: true },
              { id: 3, value: '典藏版', available: false }
            ]
          },
          {
            id: 2,
            name: '包装',
            options: [
              { id: 4, value: '简装', available: true },
              { id: 5, value: '礼盒装', available: true }
            ]
          }
        ],
        detailContent: `
          <h3>图书简介</h3>
          <p>这是一本关于${categories[categoryId-1]}的优秀图书，内容详实，观点新颖。</p>
          <h3>作者介绍</h3>
          <p>作者是业内知名专家，拥有丰富的写作经验和专业知识。</p>
          <h3>目录</h3>
          <ul>
            <li>第一章 引言</li>
            <li>第二章 主要内容</li>
            <li>第三章 案例分析</li>
            <li>第四章 总结与展望</li>
          </ul>
        `
      }
    },

    showSpecModal() {
      this.showModal = true
    },

    hideSpecModal() {
      this.showModal = false
    },

    selectSpec(option) {
      if (!option.available) return
      this.selectedSpec = option.id
    },

    getSpecName(specId) {
      for (const spec of this.productDetail.specifications) {
        const option = spec.options.find(opt => opt.id === specId)
        if (option) return option.value
      }
      return ''
    },

    increaseQuantity() {
      if (this.quantity < this.productDetail.stock) {
        this.quantity++
      }
    },

    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },

    addToCart() {
      if (!this.selectedSpec) {
        uni.showToast({ title: '请选择规格', icon: 'none' })
        return
      }

      let cart = uni.getStorageSync('cart') || []
      const productToAdd = {
        id: this.productDetail.id,
        title: this.productDetail.title,
        price: this.productDetail.price,
        cover: this.productDetail.images[0],
        stock: this.productDetail.stock,
        selectedSpec: this.selectedSpec,
        specName: this.getSpecName(this.selectedSpec),
        quantity: this.quantity,
        selected: true
      }
      
      // 检查是否已存在相同商品和规格
      const existingItem = cart.find(item => 
        item.id === productToAdd.id && item.selectedSpec === productToAdd.selectedSpec
      )
      
      if (existingItem) {
        if (existingItem.quantity + this.quantity <= this.productDetail.stock) {
          existingItem.quantity += this.quantity
        } else {
          uni.showToast({ title: '库存不足', icon: 'none' })
          return
        }
      } else {
        cart.push(productToAdd)
      }
      
      uni.setStorageSync('cart', cart)
      uni.showToast({ title: '添加成功', icon: 'success' })
      this.hideSpecModal()
      
      // 更新购物车数量
      this.updateCartCount()
      this.updateCartBadge()
    },

    buyNow() {
      if (!this.selectedSpec) {
        uni.showToast({ title: '请选择规格', icon: 'none' })
        return
      }

      const orderItems = [{
        id: this.productDetail.id,
        title: this.productDetail.title,
        price: this.productDetail.price,
        cover: this.productDetail.images[0],
        selectedSpec: this.selectedSpec,
        specName: this.getSpecName(this.selectedSpec),
        quantity: this.quantity
      }]
      
      uni.setStorageSync('tempOrder', orderItems)
      this.hideSpecModal()
      uni.navigateTo({
        url: '/pages/order/confirm'
      })
    },

    toggleFavorite() {
      this.isFavorited = !this.isFavorited
      
      let favorites = uni.getStorageSync('favorites') || []
      if (this.isFavorited) {
        if (!favorites.find(item => item.id === this.productDetail.id)) {
          favorites.push(this.productDetail)
        }
      } else {
        favorites = favorites.filter(item => item.id !== this.productDetail.id)
      }
      
      uni.setStorageSync('favorites', favorites)
      uni.showToast({ 
        title: this.isFavorited ? '已收藏' : '已取消收藏', 
        icon: 'success' 
      })
    },

    checkFavoriteStatus() {
      const favorites = uni.getStorageSync('favorites') || []
      this.isFavorited = favorites.some(item => item.id === this.productDetail.id)
    },

    goToCart() {
      uni.switchTab({
        url: '/pages/cart/cart'
      })
    },

    goToReviewList() {
      uni.navigateTo({
        url: `/pages/review/list?id=${this.productId}`
      })
    },

    previewImage(images, currentIndex) {
      uni.previewImage({
        urls: images,
        current: currentIndex
      })
    },

    shareProduct() {
      uni.share({
        title: this.productDetail.title,
        desc: this.productDetail.subtitle,
        path: `/pages/detail/detail?id=${this.productId}`,
        success: () => {
          uni.showToast({ title: '分享成功', icon: 'success' })
        }
      })
    },

    goBack() {
      uni.navigateBack()
    },

    updateCartCount() {
      const cart = uni.getStorageSync('cart') || []
      this.cartCount = cart.reduce((sum, item) => sum + item.quantity, 0)
    },

    updateCartBadge() {
      if (this.cartCount > 0) {
        uni.setTabBarBadge({
          index: 2,
          text: this.cartCount > 99 ? '99+' : this.cartCount.toString()
        })
      } else {
        uni.removeTabBarBadge({ index: 2 })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120rpx;
}

.detail-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  z-index: 10;
  border-bottom: 1rpx solid #eee;
}

.icon-back, .icon-share {
  font-size: 48rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
}

.product-swiper {
  width: 100%;
  height: 600rpx;
  margin-top: 88rpx;
}

.swiper-image {
  width: 100%;
  height: 100%;
  display: block;
}

.product-info {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.price-section {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.current-price {
  font-size: 48rpx;
  color: #ff6b6b;
  font-weight: bold;
  margin-right: 20rpx;
}

.original-price {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
  margin-right: 20rpx;
}

.discount {
  background: #ff6b6b;
  color: #fff;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.product-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.product-subtitle {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.sales-info {
  display: flex;
  justify-content: space-between;
  font-size: 24rpx;
  color: #999;
}

.spec-section, .review-section, .detail-section {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.selected-spec {
  display: flex;
  align-items: center;
  color: #666;
}

.placeholder {
  color: #999;
}

.arrow {
  margin-left: 10rpx;
  color: #999;
}

.review-title {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.review-rating {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.rating-score {
  font-size: 28rpx;
  color: #ff6b6b;
  font-weight: bold;
}

.rating-stars {
  color: #ffa726;
  font-size: 24rpx;
}

.more-info {
  display: flex;
  align-items: center;
  color: #666;
}

.review-count {
  font-size: 24rpx;
  margin-right: 10rpx;
}

.featured-reviews {
  margin-top: 20rpx;
}

.review-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.reviewer-info {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.reviewer-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 15rpx;
}

.reviewer-name {
  font-size: 26rpx;
  color: #333;
  margin-right: 20rpx;
}

.review-time {
  font-size: 22rpx;
  color: #999;
}

.review-content {
  margin-left: 75rpx;
}

.review-text {
  font-size: 28rpx;
  line-height: 1.5;
  margin-bottom: 15rpx;
  display: block;
}

.review-images {
  display: flex;
  gap: 10rpx;
}

.review-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  display: block;
}

.detail-content {
  font-size: 28rpx;
  line-height: 1.6;
}

.detail-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #eee;
  padding: 0 20rpx;
}

.footer-actions {
  display: flex;
  flex: 1;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 20rpx;
  font-size: 20rpx;
  position: relative;
}

.icon-favorite, .icon-cart {
  font-size: 40rpx;
  margin-bottom: 8rpx;
}

.icon-favorite.favorited {
  color: #ff6b6b;
}

.action-text {
  font-size: 20rpx;
  color: #333;
}

.cart-badge {
  position: absolute;
  top: 0;
  right: 10rpx;
  background: #ff6b6b;
  color: #fff;
  font-size: 20rpx;
  min-width: 30rpx;
  height: 30rpx;
  border-radius: 15rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.footer-buttons {
  display: flex;
  flex: 2;
}

.btn-add-cart, .btn-buy-now {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  margin-left: 20rpx;
  border: none;
}

.btn-add-cart {
  background: #ffa726;
  color: #fff;
}

.btn-buy-now {
  background: #ff6b6b;
  color: #fff;
}

/* 规格选择弹窗 */
.spec-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 100;
}

.modal-content {
  background: #fff;
  border-radius: 30rpx 30rpx 0 0;
  max-height: 80vh;
  overflow-y: auto;
  width: 100%;
}

.modal-header {
  display: flex;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
}

.modal-product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
  display: block;
}

.modal-product-info {
  flex: 1;
}

.modal-price {
  display: block;
  font-size: 36rpx;
  color: #ff6b6b;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.modal-stock, .modal-selected {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 5rpx;
}

.modal-close {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  font-size: 40rpx;
  color: #999;
}

.modal-specs {
  padding: 30rpx;
}

.spec-group {
  margin-bottom: 30rpx;
}

.spec-label {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.spec-option {
  padding: 16rpx 30rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #333;
}

.spec-option.active {
  border-color: #ff6b6b;
  color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
}

.spec-option.disabled {
  color: #ccc;
  background: #f5f5f5;
  border-color: #eee;
}

.quantity-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.quantity-label {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  text-align: center;
  line-height: 60rpx;
  font-size: 28rpx;
  background: #f5f5f5;
  color: #333;
}

.quantity-btn.disabled {
  color: #ccc;
  background: #f0f0f0;
}

.quantity-value {
  width: 80rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
}

.modal-actions {
  display: flex;
  padding: 20rpx 30rpx;
  gap: 20rpx;
}

.modal-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.modal-btn.add-cart {
  background: #ffa726;
  color: #fff;
}

.modal-btn.buy-now {
  background: #ff6b6b;
  color: #fff;
}
</style>